<template>
  <DetailsFormBox title="业务开单" :type="route.query.type" isFull :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: route.query.xieYiShuHao ? '保存' : '仅保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并确认',
      icon: '',
      type: 'primary',
      hidden: !isEdit || !!route.query.xieYiShuHao,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <MainBox :margin="0" :widthLeft="300" :widthRight="360">
        <template #right v-if="!!!route.query.xieYiShuHao">
          <BasicInformation :data="form" :isEdit="isEdit" @changeBtn="getProducs" />
        </template>
        <template #default>
          <template v-if="form.customerCode">
            <template v-if="form.saleOrderList?.length === 0">
              <ProducsList :data="pupProduct" @searchBtn="getProducs" @selectBtn="selectBtn" />
            </template>
            <template v-else>
              <div class="producsBox list-b-8">
                <template v-for="(item, index) in form.saleOrderList">
                  <div class="comBox producsBox-item"
                    v-if="(item.xieYiShuHao === route.query.xieYiShuHao || !!!route.query.xieYiShuHao) && item.isDisabled === 0">
                    <div class="comBox-head">
                      <div class="comBox-left">
                        <span>{{ `协议书号：${item.xieYiShuHao}` }}</span>
                      </div>
                      <div class="comBox-right" v-if="isEdit && !!!route.query.xieYiShuHao">
                        <el-link type="primary" icon="Delete" @click.stop="() => {
                          form.saleOrderList.splice(index, 1)
                        }">删除</el-link>
                        <!-- <el-divider direction="vertical" />
                      <el-link type="primary" icon="Refresh" @click.stop="refreshBtn(item)">更新数据</el-link> -->
                      </div>
                    </div>
                    <div class="comBox-main">
                      <ProducsInformation :data="item" :index="index" :isEdit="isEdit"
                        :formProp="`saleOrderList[${index}]`" :hasEditPower="form.hasEditPower" />
                    </div>
                  </div>
                </template>
                <el-button icon="Plus" class="wAuto" @click="() => {
                  pupProduct.state = true
                  pupProduct.search.likeWords = ''
                  getProducs()
                }" v-if="isEdit && !!!route.query.xieYiShuHao">添加产品</el-button>
              </div>
            </template>
          </template>
          <ElEmpty text="请先选择客户" v-else />
        </template>
      </MainBox>
    </template>
  </DetailsFormBox>
  <ElPupBox isBg :pup="pupProduct">
    <ProducsList :data="pupProduct" @searchBtn="getProducs" @selectBtn="selectBtn" />
  </ElPupBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import BasicInformation from '@/views/business/placeAnOrderNew/template/BasicInformation.vue';
import ProducsInformation from '@/views/business/placeAnOrderNew/template/ProducsInformation.vue';
import ProducsList from '@/views/business/placeAnOrderNew/template/ProducsList.vue';
import { useRoute } from 'vue-router';
import '../pageCss.scss'; // 引入样式
import { useListComponent } from '../pageTs'; // 引入逻辑
const { dataInfo } = useListComponent();
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    saleOrderGroupCode: "", // 唯一编码
    saleOrderGroupNumber: "", // 订单编号
    customerCode: "", // 客户编码
    customerName: "", // 客户名称
    saleOrderGroupState: 0, // 订单状态：0待确认；1已确认；2作废；3撤单；4已完成
    creatorName: "", // 下单人
    creator: "", // 下单人编号
    createTime: "", // 下单时间
    orderTotalAmount: 0.0, // 订单总金额
    discountType: 0, // 订单折扣类型：0无折扣；1抹元；2抹角；3抹分
    discountAmount: 0.0, // 折扣金额
    actualAmount: 0.0, // 实际金额
    cancelReason: "", // 撤单原因
    disabledReason: "", // 作废原因
    hasEditPower: true, // 是否拥有编辑权限
    saleOrderList: [],
  },
});
const isEdit = ref(true)
const options = reactive({
  //产品列表
  product: [],
});
const pupProduct: any = reactive({
  state: false,
  title: '选择产品', //
  theadCode: 'ProductManager', //
  //产品列表
  search: {
    pageIndex: 1,
    pageSize: 30,
    queryDataBaseFiled: "productName",
    likeWords: "",
    customerCode: '',
    totalCount: 0,
    state: 0
  },
  tbodyList: 4,
  tbody: [],//产品数据
  thead: [],//
});
// 获取当前路由对象
const route = useRoute();
//选择产品数据
const selectBtn = (row: any) => {
  let _form: any = data.form
  pupProduct.state = false
  proxy.$api.OrderBusniess
    .GetSingleProductByProductCode({
      queryBy: 2,
      queryValue: row.productCode,
    })
    .then((res: any) => {
      _form.saleOrderList.push({
        xieYiShuHao: "系统自动生成", //产品编码
        productCode: res.baseData.productCode, //产品编码
        customerBillNo: "", //客户单号
        deliveryDate: "", //交货日期
        productQuantity: 0, //产品数量
        dataComeFrom: null, //数据来源：0无、1客户、2自编
        isProductionRequired: null, //是否生产 0-不需要；1-需要
        paymentMethod: 0, //计价方式
        dataQuantity: 0, //数据数量
        isDisabled: 0, //是否禁用
        remark: "", //备注
        unitPrice: res.baseData.productPrice, //下单单价
        totalAmount: 0, //小计金额
        contractName: "", //合同名称
        contractFile: "", //合同文件路径
        productLayout: "", //订单产品版面
        orderProduct: res.baseData, //产品信息
        productColorDraftFileList: res.productColorDraftFileList, //彩稿信息
        productSpecificationList: res.productSpecificationList, //产品型号
        productSteppedPriceInfoList: res.productSteppedPriceInfoList, //产品阶梯价信息
        orderProductSpecificationList: [{
          ...res.productSpecificationList[0],//产品型号
          productionQuantity: null,//	生产数量
          deliveredQuantity: 0,//已发货数量（成品出库时回写）
          remark: "",//备注
        }],//订单型号信息
        orderProductSpecificationListArr: [res.productSpecificationList[0].productSpecificationCode],//
        productionProgressList: [],//生产进度
        costList: [],//其他费用
      })
    });
};
//更新产品数据
const refreshBtn = (row: any) => {
  proxy.$api.OrderBusniess
    .GetSingleProductByProductCode({
      queryBy: 2,
      queryValue: row.productCode,
    })
    .then((res: any) => {
      row.productColorDraftFileList = res.productColorDraftFileList //彩稿信息
      row.productSpecificationList = res.productSpecificationList //产品型号
      row.productSteppedPriceInfoList = res.productSteppedPriceInfoList //产品阶梯价信息
      row.orderProduct = res.baseData//产品信息
      row.unitPrice = res.baseData.productPrice //下单单价
    });
};
//获取产品数据
const getProducs = (customerCode: string = data.form.customerCode) => {
  proxy.$api.OrderBusniess.GetPageProductList({
    ...pupProduct.search,
    customerCode: customerCode,//客户编号
  })
    .then((res: any) => {
      pupProduct.tbody = res.list
      pupProduct.search.totalCount = res.totalCount
    })
    .catch(() => {
    });
};
//获取数据
const getForm = () => {
  let _query: any = route.query
  if (!_query.saleOrderGroupCode) {
    return
  }
  setLoading()
  proxy.$api.OrderBusniess.GetSaleOrderGroupDetail({
    saleOrderGroupCode: _query.saleOrderGroupCode,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = (['1', '2'].includes(_query.type) && res.saleOrderGroupState === 0) || route.query.xieYiShuHao
      data.form = {
        ...res,
        saleOrderList: res.saleOrderList.map((el: any) => ({
          ...el,
          orderProductSpecificationListArr: el.orderProductSpecificationList?.map((item: any) => item.productSpecificationCode),
          costList: [],//其他费用
        }))
      }
      getProducs(res.customerCode)
      costList()
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const costList = () => {
  data.form.saleOrderList.forEach((el: any, index: any) => {
    proxy.$api.OrderBusniess
      .GetMatchPageSaleOrderFeeDetails({
        pageIndex: 1,
        pageSize: 1000,
        queryDataBaseFiled: "",
        likeWords: "",
        onlySelf: 0,
        isShowDisabled: 0,
        orderByFiled: "",
        orderByType: 0,
        saleOrderCode: el.saleOrderCode,
        reconciliationStatus: 0,
      })
      .then((res: any) => {
        el.costList = res.list
      })
      .catch(() => {

      });
  });
}
const saveBtn = (form: any, isConfirm: boolean = false) => {
  if (form.saleOrderGroupCode) {
    proxy.$api.OrderBusniess.UpdateSaleOrderGroup(form)
      .then((res: any) => {
        if (isConfirm) {
          _setState(form.saleOrderGroupCode)
        } else {
          _sun()
        }
      })
      .catch(() => { });
  } else {
    proxy.$api.OrderBusniess.AddSaleOrderGroup(form)
      .then((res: any) => {
        if (isConfirm) {
          _setState(res.saleOrderGroupCode)
        } else {
          _sun()
        }
      })
      .catch(() => { });
  }

  function _sun() {
    proxy.$message('保存成功')
    sendMsg('save', true);
    // getForm()
    window.close();
  }
  function _setState(saleOrderGroupCode: string) {
    proxy.$api.OrderBusniess.UpdateSaleOrderGroupState({
      saleOrderGroupCode: saleOrderGroupCode, //分组订单编码
      state: 1, //订单状态：0待确认；1已确认；2作废；3撤单；4已完成；
      reason: '', //作废原因/撤单原因
    })
      .then((res: any) => {
        _sun()
      })
      .catch(() => {
        _sun()
      });
  }
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
onMounted(() => {
  getForm();
});
</script>
